<?php


namespace app\middleware;


use app\BaseController;
use app\common\exception\BaseException;
use app\common\tool\HttpCode;
use app\libs\exception\AuthFailed;
use app\libs\tool\JwtAuth;
use think\Exception;
use think\Request;
use think\Response;

class Auth
{
    /**
     * @throws \app\libs\exception\AuthFailed
     */
    public function handle($request, \Closure $next): Response
    {
        $jwtAuth = new JwtAuth(
            config('secure.jwt_alg'),
            config('secure.verify_salt')
        );

        // 获取访问用户的token, 使用Authorization 字段
        $token = $request->header('Authorization', '');

        // 前后端分离规范, 还有JWT校验格式, 提交上来的Token 前面的Bearer 需要去掉
        $token = str_replace('Bearer ', '', $token);

        $result = $jwtAuth->verify($token);
        if ($result['code'] !== 1) throw new AuthFailed();

        $request->userInfo = $result['data'];

        return $next($request);
    }
}